package com.learning.spring.cloud.alibaba.ribbon.user.web.controller;

import com.learning.spring.cloud.alibaba.ribbon.user.web.model.User;
import com.learning.spring.cloud.alibaba.ribbon.user.web.service.IUserService;
import com.learning.spring.cloud.alibaba.ribbon.user.web.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName: UserController
 * Description:
 * Date: 2021/7/25 23:03 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Integer insert(@RequestBody User user) {
        return userService.insert(user);
    }

    /**
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public Integer deleteByPrimaryKey(@PathVariable("id") Long id) {
        return userService.deleteByPrimaryKey(id);
    }


    @Resource
    RestTemplate restTemplate;

    /**
     * http://localhost:8001/user/query/1
     *
     * @param id
     * @return
     */
    @GetMapping("/query/{id}")
    public UserVo selectByPrimaryKey(@PathVariable("id") Long id) {
        UserVo userVo = new UserVo();
        User user = userService.selectByPrimaryKey(id);

        // 访问订单服务
        List<String> orderNameList = this.restTemplate.getForObject("http://01-ms-ribbon-order/order/query/user/" + id, List.class);

        userVo.setOrderNameList(orderNameList);
        userVo.setId(user.getId());
        userVo.setName(user.getName());
        return userVo;
    }
}
